<!DOCTYPE HTML>
<html lang="zh-CN">


<head>
    <meta charset="utf-8">
    <meta name="keywords" content="R语言与数据分析（一）, 幽狼的博客">
    <meta name="description" content="无论处境，泰然处之">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <!-- Global site tag (gtag.js) - Google Analytics -->


    <title>R语言与数据分析（一） | 幽狼的博客</title>
    <link rel="icon" type="image/png" href="/auther2.png">

    <link rel="stylesheet" type="text/css" href="/libs/awesome/css/all.css">
    <link rel="stylesheet" type="text/css" href="/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/css/my.css">

    <script src="/libs/jquery/jquery.min.js"></script>

<meta name="generator" content="Hexo 5.4.0"></head>




<body>
    <header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/" class="waves-effect waves-light">
                    
                    <img src="/auther2.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">幽狼的博客</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/" class="waves-effect waves-light">
      
      <i class="fas fa-home" style="zoom: 0.6;"></i>
      
      <span>首页</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/tags" class="waves-effect waves-light">
      
      <i class="fas fa-tags" style="zoom: 0.6;"></i>
      
      <span>标签</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/categories" class="waves-effect waves-light">
      
      <i class="fas fa-bookmark" style="zoom: 0.6;"></i>
      
      <span>分类</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/archives" class="waves-effect waves-light">
      
      <i class="fas fa-archive" style="zoom: 0.6;"></i>
      
      <span>归档</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/about" class="waves-effect waves-light">
      
      <i class="fas fa-user-circle" style="zoom: 0.6;"></i>
      
      <span>关于</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/contact" class="waves-effect waves-light">
      
      <i class="fas fa-comments" style="zoom: 0.6;"></i>
      
      <span>留言板</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="" class="waves-effect waves-light">

      
      <i class="fas fa-list" style="zoom: 0.6;"></i>
      
      <span>Medias</span>
      <i class="fas fa-chevron-down" aria-hidden="true" style="zoom: 0.6;"></i>
    </a>
    <ul class="sub-nav menus_item_child ">
      
      <li>
        <a href="/books">
          
          <i class="fas fa-book" style="margin-top: -20px; zoom: 0.6;"></i>
          
          <span>书单</span>
        </a>
      </li>
      
      <li>
        <a href="/movies">
          
          <i class="fas fa-film" style="margin-top: -20px; zoom: 0.6;"></i>
          
          <span>电影</span>
        </a>
      </li>
      
      <li>
        <a href="/galleries">
          
          <i class="fas fa-image" style="margin-top: -20px; zoom: 0.6;"></i>
          
          <span>相册</span>
        </a>
      </li>
      
      <li>
        <a href="/games">
          
          <i class="fas fa-file-alt" style="margin-top: -20px; zoom: 0.6;"></i>
          
          <span>游戏</span>
        </a>
      </li>
      
    </ul>
    
  </li>
  
  <li>
    <a href="#searchModal" class="modal-trigger waves-effect waves-light">
      <i id="searchIcon" class="fas fa-search" title="搜索" style="zoom: 0.85;"></i>
    </a>
  </li>
</ul>


<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/auther2.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">幽狼的博客</div>
        <div class="logo-desc">
            
            无论处境，泰然处之
            
        </div>
    </div>

    

    <ul class="menu-list mobile-menu-list">
        
        <li class="m-nav-item">
	  
		<a href="/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-home"></i>
			
			首页
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/tags" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-tags"></i>
			
			标签
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/categories" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-bookmark"></i>
			
			分类
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/archives" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-archive"></i>
			
			归档
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/about" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-user-circle"></i>
			
			关于
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/contact" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-comments"></i>
			
			留言板
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="javascript:;">
			
				<i class="fa-fw fas fa-list"></i>
			
			Medias
			<span class="m-icon"><i class="fas fa-chevron-right"></i></span>
		</a>
            <ul  style="background:  ;" >
              
                <li>

                  <a href="/books " style="margin-left:75px">
				  
				   <i class="fa fas fa-book" style="position: absolute;left:50px" ></i>
			      
		          <span>书单</span>
                  </a>
                </li>
              
                <li>

                  <a href="/movies " style="margin-left:75px">
				  
				   <i class="fa fas fa-film" style="position: absolute;left:50px" ></i>
			      
		          <span>电影</span>
                  </a>
                </li>
              
                <li>

                  <a href="/galleries " style="margin-left:75px">
				  
				   <i class="fa fas fa-image" style="position: absolute;left:50px" ></i>
			      
		          <span>相册</span>
                  </a>
                </li>
              
                <li>

                  <a href="/games " style="margin-left:75px">
				  
				   <i class="fa fas fa-file-alt" style="position: absolute;left:50px" ></i>
			      
		          <span>游戏</span>
                  </a>
                </li>
              
            </ul>
          
        </li>
        
        
    </ul>
</div>


        </div>

        
    </nav>

</header>

    



<div class="bg-cover pd-header post-cover" style="background-image: url('/medias/featureimages/12.jpg')">
    <div class="container" style="right: 0px;left: 0px;">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <h1 class="description center-align post-title">R语言与数据分析（一）</h1>
                </div>
            </div>
        </div>
    </div>
</div>




<main class="post-container content">

    
    <link rel="stylesheet" href="/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        width: 345px;
        padding-left: 20px;
        margin: 0.5rem 0px 0rem 0px;
    }

    .toc-widget .toc-title {
        padding: 35px 0 15px 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content {
        padding-bottom: 30px;
        overflow: auto;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;

        position: absolute;
        right: 23.5vw;
        display: block;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 15px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/tags/R%E8%AF%AD%E8%A8%80%E6%95%B0%E6%8D%AE%E5%88%86%E6%9E%90/">
                                <span class="chip bg-color">R语言数据分析</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fas fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/categories/%E6%95%B0%E6%8D%AE%E5%88%86%E6%9E%90/" class="post-category">
                                数据分析
                            </a>
                        
                    </div>
                    
                </div>
            </div>

            <div class="post-info">
                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-minus fa-fw"></i>发布日期:&nbsp;&nbsp;
                    2020-06-26
                </div>
                

                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-check fa-fw"></i>更新日期:&nbsp;&nbsp;
                    2023-09-10
                </div>
                

                

                

                
                    <div id="busuanzi_container_page_pv" class="info-break-policy">
                        <i class="far fa-eye fa-fw"></i>阅读次数:&nbsp;&nbsp;
                        <span id="busuanzi_value_page_pv"></span>
                    </div>
				
            </div>
        </div>
        <hr class="clearfix">

        
        <!-- 是否加载使用自带的 prismjs. -->
        <link rel="stylesheet" href="/libs/prism/prism.css">
        

        

        <div class="card-content article-card-content">
            <div id="articleContent">
                <blockquote class="blockquote-center">
喜欢一件事就去争取吧。
</blockquote>
<span id="more"></span>


<h2 id="1-课程介绍"><a href="#1-课程介绍" class="headerlink" title="1. 课程介绍"></a>1. 课程介绍</h2><h2 id="2-数据分析"><a href="#2-数据分析" class="headerlink" title="2. 数据分析"></a>2. 数据分析</h2><p>数据就是事物进行记录可鉴别的符号，是对客观事物性质状态以及相互关系等进行记载的物理符号。</p>
<p><strong>数据分析过程</strong>：</p>
<ol>
<li>数据的采集</li>
<li>数据的存储</li>
<li>数据统计：使用统计方法，有目的的对收集的数据进行分析处理，并解读分析结果。结绳、算盘、计算器、excel</li>
<li>数据挖掘：一般是指从大量的数据中通过算法搜索隐藏于其中的信息的过程。挖掘是一个探索的过程，统计是有目的的。</li>
<li>数据的可视化 </li>
<li>进行决策，利用统计结果进行有目的的决策</li>
</ol>
<h2 id="3-数据挖掘"><a href="#3-数据挖掘" class="headerlink" title="3. 数据挖掘"></a>3. 数据挖掘</h2><p>介绍了数据挖掘的重要性。</p>
<h2 id="4-数据可视化"><a href="#4-数据可视化" class="headerlink" title="4. 数据可视化"></a>4. 数据可视化</h2><p>人是视觉动物</p>
<h2 id="5-R语言介绍"><a href="#5-R语言介绍" class="headerlink" title="5. R语言介绍"></a>5. R语言介绍</h2><ol>
<li>有效的数据处理和保存机制。</li>
<li>拥有一整套数组和矩阵的操作运算符</li>
<li>一系列连贯而又完整的数据分析中间工具</li>
<li>图形统计可以对数据直接进行分析和显示，可用于多种图形设备</li>
<li>一种相当完善、简介和搞笑的程序设计语言</li>
<li>R语言是彻底的面向对象的统计编程语言</li>
<li>R语言和其他变成语言、数据库之有很好的接口</li>
<li>R语言是自由 的软件，功能不比任何其他同列软件差</li>
<li>R语言的网上资源丰富</li>
</ol>
<p>Rebolutions R 已经被微软收购了，该命为Microsoft R </p>
<h2 id="6-R应用的案例"><a href="#6-R应用的案例" class="headerlink" title="6. R应用的案例"></a>6. R应用的案例</h2><p>一个维生素C与牙齿生长的关系</p>
<p>在官网上面下载R语言的安装包，</p>
<h2 id="7-R语言的安装"><a href="#7-R语言的安装" class="headerlink" title="7. R语言的安装"></a>7. R语言的安装</h2><p>不着急，这个在网络上有大量的资源</p>
<h2 id="8-R-运行与设置"><a href="#8-R-运行与设置" class="headerlink" title="8. R 运行与设置"></a>8. R 运行与设置</h2><p>讲述了R自带的GUI</p>
<h2 id="9-Rstudio"><a href="#9-Rstudio" class="headerlink" title="9. Rstudio"></a>9. Rstudio</h2><p>一般都是用到了这个软件， 介绍了各种界面的操作。</p>
<h2 id="10-基本操作"><a href="#10-基本操作" class="headerlink" title="10 基本操作"></a>10 基本操作</h2><p>设定工作目录，查看工作目录</p>
<blockquote>
<p>getwd() </p>
</blockquote>
<p>设置工作目录，填入你的工作目录</p>
<blockquote>
<p>setwd(dir = “”)</p>
</blockquote>
<p>列出每个变量的所有信息</p>
<blockquote>
<p>ls.str() </p>
</blockquote>
<h2 id="11-R扩展包"><a href="#11-R扩展包" class="headerlink" title="11. R扩展包"></a>11. R扩展包</h2><p>查看扩展包的位置</p>
<blockquote>
<p>.libPaths()</p>
</blockquote>
<p>查看安装了哪些安装包</p>
<blockquote>
<p>library()</p>
</blockquote>
<p>一次安装多个包</p>
<blockquote>
<p>install.packages(c(“AER”,”ca”,””)</p>
</blockquote>
<h2 id="12-R包的使用"><a href="#12-R包的使用" class="headerlink" title="12 R包的使用"></a>12 R包的使用</h2><p>R软件包的组成</p>
<ul>
<li>base</li>
<li>datasets 存放R内置的数据集</li>
<li>utils R语言的工具函数</li>
<li>grDevices 基于base 和greph的图形设备，与绘图相关的函数都在这个包里</li>
<li>graphics 基于base图形的R默认的绘图函数都在这个包里</li>
<li>stats 存放与统计相关的函数，</li>
<li>methods R对象一般的定义方法和类</li>
<li>splines 基础包</li>
<li>stats4 基础包</li>
<li>tcltk 基础包</li>
</ul>
<p>广州,兰州,的镜像是可以用的,兰州是比较快的.</p>
<p>加载包</p>
<blockquote>
<p>require(vcd)</p>
</blockquote>
<p>移除加载</p>
<blockquote>
<p>detach(“package:vcd”)</p>
</blockquote>
<p>删除包</p>
<blockquote>
<p>remove.package(“vcd”)</p>
</blockquote>
<p>查看以安装的包</p>
<blockquote>
<p>installed.packages()</p>
</blockquote>
<p>查看工具包的帮助信息</p>
<blockquote>
<p>help(package=”vcd”)</p>
</blockquote>
<p>也可以用library来查看帮助信息</p>
<blockquote>
<p>library(help=”vcd”)</p>
</blockquote>
<p>列出vcd中所有包含的函数</p>
<blockquote>
<p>ls(“package:vcd”)</p>
</blockquote>
<p>列出vcd中所有的数据集</p>
<blockquote>
<p>data(package=”vcd”)</p>
</blockquote>
<h3 id="R包的批量移植"><a href="#R包的批量移植" class="headerlink" title="R包的批量移植"></a>R包的批量移植</h3><p>一种方案:</p>
<blockquote>
<p>Rpackage &lt;- installed.packages()[,1]<br>save(Rpackage,file=”Rpack.Rdata)</p>
</blockquote>
<p>列出安装包的第一列,导出到一个文本中,在另一个电脑上load加载到一个变量中,</p>
<blockquote>
<p>for (i in Rpack) install.packages(i)<br>这样就可以批量安装包了.</p>
</blockquote>
<h2 id="13-获取帮助"><a href="#13-获取帮助" class="headerlink" title="13 获取帮助"></a>13 获取帮助</h2><p>比如help()会在浏览器中打开帮助信息,和?sum一个意思</p>
<blockquote>
<p>help(sum)</p>
</blockquote>
<blockquote>
<p>?(sum)</p>
</blockquote>
<p>快速了解函数的参数,而不想去看文档args函数</p>
<blockquote>
<p>args(plot)</p>
</blockquote>
<p>还可以用esample 函数去示例一个函数的使用</p>
<blockquote>
<p>example(hist)</p>
</blockquote>
<p>也可以用demo 这种示例</p>
<blockquote>
<p>demo(graphic)</p>
</blockquote>
<p>用help查看包的帮助,这个是在网上查看帮助信息</p>
<blockquote>
<p>help(package=vcd)</p>
</blockquote>
<p>用vignette()函数,这个一些库可能没有这个文档,</p>
<blockquote>
<p>vignette(“vcd”)</p>
</blockquote>
<blockquote>
<p>??qplot</p>
</blockquote>
<p>网络搜索相关的函数</p>
<blockquote>
<p>RSiteSearch(“matlab”)</p>
</blockquote>
<p>rseek.org 是一个与R相关的论坛</p>
<h2 id="14-excel-案例"><a href="#14-excel-案例" class="headerlink" title="14 excel 案例"></a>14 excel 案例</h2><p>主要是excel 数据透视表的使用案例,没有数据不是很懂,老师也说了,excel也是一种很强大的数据分析工具,也可以学习excel的使用</p>
<h2 id="15-内置数据集"><a href="#15-内置数据集" class="headerlink" title="15 内置数据集"></a>15 内置数据集</h2><p>R内置了很多的数据集,存在于datasets这个包中</p>
<p>直接<code>data()</code>就可以列出很多的数据集,<code>rivers</code>可以列出北美141条河流的长度</p>
<p>可以用<code>help(&quot;mtcars&quot;)</code>这样的去查看数据的帮助信息</p>
<p>加载数据集</p>
<blockquote>
<p>data(package=”MASS”)</p>
</blockquote>
<p>这样只是加载数据集,而包就不用加载进来</p>
<blockquote>
<p>data(Chile,Package=”car”)</p>
</blockquote>
<h2 id="16-数据结构"><a href="#16-数据结构" class="headerlink" title="16 数据结构"></a>16 数据结构</h2><p>数据结构式计算机存储、组织数据的方式。数据结构是指相互之间存在一种或多种特定关系的数据元素集合。</p>
<p>这个是很重要的，知道是什么，知道为什么。</p>
<p>R中数据类型</p>
<ol>
<li>数值型，数值可以用于直接计算。</li>
<li>字符串型，可以进行连接，转换，提取等。</li>
<li>逻辑型，真假。</li>
<li>日期型等。</li>
</ol>
<p>这个跟Python差不多。</p>
<p>普通的数据结构：向量，标量，列表，数组，多维数组。</p>
<p>特殊数据结构：perl中的哈希，python中的字典，c语言中的指针等。</p>
<p>R对象：object, 他是指可以赋值给变量的任何事物，包括常量，数据结构，函数，甚至图形。对象都拥有某种模式，描述了此对象是如何存储的，以及某个类。</p>
<h2 id="17-向量"><a href="#17-向量" class="headerlink" title="17 向量"></a>17 向量</h2><p>向量，vector, 是R中最重要的一个概念，它是构成其他数据结构的基础，R中的向量概念和数学中的向量是不同的，类似于数学上的集合，有一个或多个元素所构成。向量其实是用于存储数值型，字符型或逻辑型数据的一维数组。</p>
<p>R中用函数 “c ”来创建向量。如：</p>
<blockquote>
<p>c &lt;- c(1,2,3,4)<br>z &lt;- c(TRUE,T,F)</p>
</blockquote>
<p>R中 <code>euro</code>,<code>rivers</code>,<code>state.abb</code>,<code>state.area</code>都是向量的数据结构。</p>
<p>等差数列,输出1到100的等差数列</p>
<blockquote>
<p>c(1:100)</p>
</blockquote>
<p>输出步长为2的等差数列</p>
<blockquote>
<p>seq (from=1,to=100,by=2)</p>
</blockquote>
<p>输出重复序列,x重复5次</p>
<blockquote>
<p>rep (“x”,5)<br>rep (x,5)</p>
</blockquote>
<p>可以用each来控制一个元素的重复次数。如下可以吧x中的元素重复5次，times可以把整数组重复2次。</p>
<blockquote>
<p>rep(x,each=5,times=2)</p>
</blockquote>
<p>如何查看数据类型，</p>
<blockquote>
<p>mode(z)</p>
</blockquote>
<p>R中向量化编程</p>
<blockquote>
<p>x &lt;- c(1,2,3,4,5)<br>y &lt;- c(6,7,8,9,10)<br>x*2+y<br>8 11 14 17 20</p>
</blockquote>
<p>在x中取出x&gt;3的值</p>
<blockquote>
<p>x[x&gt;3]</p>
</blockquote>
<p>使用rep来控制每个元素的出现次数</p>
<blockquote>
<p>rep(x,c(2,4,6,1,3))<br>输出[1] 1 1 2 2 2 2 3 3 3 3 3 3 4 5 5 5</p>
</blockquote>
<h2 id="18-向量索引"><a href="#18-向量索引" class="headerlink" title="18 向量索引"></a>18 向量索引</h2><p>在R中元素的第一个值是从 “1” 开始，不是0<code>length(x)</code>可以算出元素的个数。<br>如：x为1-100的元组</p>
<blockquote>
<p>x[c(1,23,55,32,78)]<br>[1]  1 23 54 65 输出</p>
</blockquote>
<p><strong>重要</strong>使用逻辑向量的值来进行向量的索引。比如：</p>
<blockquote>
<p>y &lt;- c(1:10)<br>y[c(T,F,T,F,T,F,T,T,T,T,T)]<br>[1]  1  3  5  7  8  9 10 NA 输出为真的数字 NA为缺失值</p>
</blockquote>
<p>又比如</p>
<blockquote>
<p>z &lt;- c(“one”,”two”, “three”, “four”, “five”)<br>z<br>[1] “one”   “two”   “three” “four”  “five”<br>z %in% c(“one”,”two”) 判断是否在z中有这个字符。<br>[1]  TRUE  TRUE FALSE FALSE FALSE</p>
</blockquote>
<p>使用元素名称进行访问，相当于字典中的键值对</p>
<pre class="line-numbers language-none"><code class="language-none">&gt; y &lt;- c(1:6)
&gt; names(y) &#x3D; c(&quot;noe&quot;, &quot;two&quot;, &quot;three&quot;, &quot;four&quot;, &quot;five&quot;, &quot;six&quot;)
&gt; y
  noe   two three  four  five   six 
    1     2     3     4     5     6 
&gt; names(y)
[1] &quot;noe&quot;   &quot;two&quot;   &quot;three&quot; &quot;four&quot;  &quot;five&quot;  &quot;six&quot; 
&gt; y[&quot;two&quot;]
two 
  2 <span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>append函数，可以指定在那个位置进行插值。</p>
<pre class="line-numbers language-R" data-language="R"><code class="language-R">&gt; x &lt;- c(1:100)
&gt; v &lt;- c(1:3)
&gt; v[15] &lt;- 15
&gt; v
 [1]  1  2  3 NA NA NA NA NA NA NA NA NA NA NA 15
&gt; append(x &#x3D; v, values &#x3D; 50,after &#x3D; 12)
 [1]  1  2  3 NA NA NA NA NA NA NA NA NA 50 NA NA 15
&gt;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>删除向量可以用<code>rm()</code>函数，也可以在索引中加负号，但只是暂时的，但是可以传回原来的值</p>
<pre class="line-numbers language-R" data-language="R"><code class="language-R">&gt; rm(y)
&gt; y &lt;- c(1:10)
&gt; y[-c(1:3)]
[1]  4  5  6  7  8  9 10

&gt; y &lt;- y[-c(1:3)]
&gt; y
[1]  4  5  6  7  8  9 10
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h2 id="19-向量的运算"><a href="#19-向量的运算" class="headerlink" title="19 向量的运算"></a>19 向量的运算</h2><p>“**”为幂运算<br>“%%”求余运算<br>“%/%”为整除运算</p>
<p>两个元素的相加必须是相同的元素个数。python中这个还是很好解决的</p>
<pre class="line-numbers language-R" data-language="R"><code class="language-R">&gt; x &#x3D; c(1,2,3)
&gt; y &#x3D; c(1,2,4,5,6)
&gt; x&gt;y
[1] FALSE FALSE FALSE FALSE FALSE
Warning message:
In x &gt; y : 长的对象长度不是短的对象长度的整倍数

&gt; c(1,2,3) %in% c(1,2,4,5,6)
[1]  TRUE  TRUE FALSE<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>其他的函数运算</p>
<pre class="line-numbers language-R" data-language="R"><code class="language-R">&gt; abs(-6) 为绝对值
[1] 6
&gt; sqrt(25)  开方
[1] 5
&gt; log(16,base&#x3D;2)
[1] 4
&gt; log2(16)  对数函数
[1] 4
&gt; ceiling(c(-2.3,3.1415))  返回整数部分
[1] -2  4
&gt; sin(x)  三角函数
[1] 0.8414710 0.9092974 0.1411200
&gt; vec &#x3D; 1:100
&gt; sum(vec)  求和函数
[1] 5050
&gt; range(vec)  范围，最大值和最小值
[1]   1 100
&gt; max(vec)  最大值
[1] 100
&gt; min(vec)  最小值
[1] 1
&gt; mean(vec)  均值
[1] 50.5
&gt; var(vec)  方差
[1] 841.6667
&gt; sd(vec)  标准差
[1] 29.01149
&gt; median(vec)  中位数
[1] 50.5
&gt; round(var(vec),digits &#x3D; 2)  round默认是整数digits设置小数位数
[1] 841.67
&gt; prod(vec)  各元素连续乘积
[1] 9.332622e+157
&gt; quantile(vec,c(0.5,0.4,0.8))  分位数
 50%  40%  80% 
50.5 40.6 80.2<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>寻找元素位置which,返回索引</p>
<pre class="line-numbers language-R" data-language="R"><code class="language-R">&gt; t &#x3D; c(1,5,4,7,2,9,6)
&gt; which.max(t)
[1] 6
&gt; which(t&#x3D;&#x3D;7)
[1] 4<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h2 id="20-矩阵与数组"><a href="#20-矩阵与数组" class="headerlink" title="20 矩阵与数组"></a>20 矩阵与数组</h2><p>矩阵式一个按照长方阵列排列的复数或实数集合.向量是一维的,而矩阵式二维的,需要有行列.基本就跟excel中的数据表差不多.</p>
<p>内置矩阵数据集</p>
<pre class="line-numbers language-R" data-language="R"><code class="language-R">&gt; iris3
&gt; state.x77
&gt; heatmap(state.x77)  热图<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>

<p>用<code>matrix()</code>创建矩阵</p>
<pre class="line-numbers language-R" data-language="R"><code class="language-R">&gt; m &#x3D; matrix(1:20,4,5)  1到20,4行5列的矩阵
&gt; m
     [,1] [,2] [,3] [,4] [,5]
[1,]    1    5    9   13   17
[2,]    2    6   10   14   18
[3,]    3    7   11   15   19
[4,]    4    8   12   16   20

&gt; m &#x3D; matrix(1:20,4,5,byrow &#x3D; T&#x2F;F) 通过行或列<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>更改行列名称</p>
<pre class="line-numbers language-R" data-language="R"><code class="language-R">&gt; rname &#x3D; c(&quot;1&quot;,&quot;2&quot;,&quot;3&quot;,&quot;4&quot;)
&gt; cname &#x3D; c(&quot;1&quot;,&quot;2&quot;,&quot;3&quot;,&quot;4&quot;,&quot;5&quot;)
&gt; dimnames(m) &#x3D; list(rname,cname)
&gt; m
  1 2  3  4  5
1 1 5  9 13 17
2 2 6 10 14 18
3 3 7 11 15 19
4 4 8 12 16 20<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p><code>dim()</code>向量设定函数</p>
<p>设定为一个2行2列的3高的三维数组</p>
<pre class="line-numbers language-R" data-language="R"><code class="language-R">&gt; x &#x3D; c(1:12)
&gt; x
 [1]  1  2  3  4  5  6  7  8  9 10 11 12 
&gt; dim(x)
NULL
&gt; dim(x) &#x3D; c(2,2,3)
&gt; x
, , 1

     [,1] [,2]
[1,]    1    3
[2,]    2    4

, , 2

     [,1] [,2]
[1,]    5    7
[2,]    6    8

, , 3

     [,1] [,2]
[1,]    9   11
[2,]   10   12<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>如何访问二维数组的值</p>
<pre class="line-numbers language-R" data-language="R"><code class="language-R">&gt; m
     [,1] [,2] [,3] [,4] [,5]
[1,]    1    5    9   13   17
[2,]    2    6   10   14   18
[3,]    3    7   11   15   19
[4,]    4    8   12   16   20
&gt; m[2,2]  二行二列
[1] 6
&gt; m[2,]  二行
[1]  2  6 10 14 18
&gt; m[,2]  二列
[1] 5 6 7 8
&gt; m[-1,2]  &quot;-&quot;为去除第一列
[1] 6 7 8

&gt; m+1  每个元素加一
     [,1] [,2] [,3] [,4] [,5]
[1,]    2    6   10   14   18
[2,]    3    7   11   15   19
[3,]    4    8   12   16   20
[4,]    5    9   13   17   21<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>行列的计算</p>
<pre class="line-numbers language-R" data-language="R"><code class="language-R">&gt; colSums(m)  计算每一列的和
[1] 10 26 42 58 74
&gt; rowSums(m)  计算每一行的和
[1] 45 50 55 60
&gt; colMeans(m)  列的平均值
[1]  2.5  6.5 10.5 14.5 18.5
&gt; rowMeans(m)  行的平均值
[1]  9 10 11 12<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>矩阵的内外积</p>
<pre class="line-numbers language-R" data-language="R"><code class="language-R">&gt; n &#x3D; matrix(1:9,3,3)
&gt; t &#x3D; matrix(2:10,3,3)
&gt; n
     [,1] [,2] [,3]
[1,]    1    4    7
[2,]    2    5    8
[3,]    3    6    9
&gt; t
     [,1] [,2] [,3]
[1,]    2    5    8
[2,]    3    6    9
[3,]    4    7   10
&gt; n*t  内积
     [,1] [,2] [,3]
[1,]    2   20   56
[2,]    6   30   72
[3,]   12   42   90

&gt; n %*% t  外积
     [,1] [,2] [,3]
[1,]   42   78  114
[2,]   51   96  141
[3,]   60  114  168<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>其他</p>
<pre class="line-numbers language-R" data-language="R"><code class="language-R">&gt; diag(n)  对角线
[1] 1 5 9
&gt; diag(t)
[1]  2  6 10

&gt; m
     [,1] [,2] [,3] [,4] [,5]
[1,]    1    5    9   13   17
[2,]    2    6   10   14   18
[3,]    3    7   11   15   19
[4,]    4    8   12   16   20
&gt; t(m)  行列转换
     [,1] [,2] [,3] [,4]
[1,]    1    2    3    4
[2,]    5    6    7    8
[3,]    9   10   11   12
[4,]   13   14   15   16
[5,]   17   18   19   20<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h2 id="21-列表"><a href="#21-列表" class="headerlink" title="21-列表"></a>21-列表</h2><p>列表顾名思义就是用来存储很多内容的集合,列表和数组基本是等同的,但是在R中,列表是最复杂的一种数据结构,也是非常重要的一种数据结构.</p>
<p>列表中可以存储若干个向量,矩阵,数据框,甚至其他的列表组合.</p>
<p>向量只能存储一种数据类型,列表却可以存储多种数据类型.</p>
<p>比如: 其实跟Python中的list是一样的</p>
<pre class="line-numbers language-R" data-language="R"><code class="language-R">&gt; a &#x3D; 1:20
&gt; b &#x3D; matrix(1:20,4)
&gt; c &#x3D; mtcars
&gt; d &#x3D; &quot;This is a test list&quot;
&gt; mlist &#x3D; list(a,b,c,d)
&gt; mlist
[[1]]
 [1]  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20

[[2]]
     [,1] [,2] [,3] [,4] [,5]
[1,]    1    5    9   13   17
[2,]    2    6   10   14   18
[3,]    3    7   11   15   19
[4,]    4    8   12   16   20

[[3]]
                     mpg cyl  disp  hp drat    wt  qsec vs am gear carb
Mazda RX4           21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4
Mazda RX4 Wag       21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4
Datsun 710          22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1
Hornet 4 Drive      21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1
Hornet Sportabout   18.7   8 360.0 175 3.15 3.440 17.02  0  0    3    2
Valiant             18.1   6 225.0 105 2.76 3.460 20.22  1  0    3    1
Duster 360          14.3   8 360.0 245 3.21 3.570 15.84  0  0    3    4
Merc 240D           24.4   4 146.7  62 3.69 3.190 20.00  1  0    4    2
Merc 230            22.8   4 140.8  95 3.92 3.150 22.90  1  0    4    2
Merc 280            19.2   6 167.6 123 3.92 3.440 18.30  1  0    4    4
Merc 280C           17.8   6 167.6 123 3.92 3.440 18.90  1  0    4    4
Merc 450SE          16.4   8 275.8 180 3.07 4.070 17.40  0  0    3    3
Merc 450SL          17.3   8 275.8 180 3.07 3.730 17.60  0  0    3    3

[[4]]
[1] &quot;This is a test list&quot;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p><code>mlist[[1]]</code> 访问的数据本身,如果是一个中括号,则数据类型是一个list.所以给列表赋值的时候要两个中括号.</p>
<pre class="line-numbers language-R" data-language="R"><code class="language-R">&gt; mlist[[5]] &#x3D; iris  
&gt; mlist[-5]  就可以删除这个索引的值<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<h2 id="22-数据框"><a href="#22-数据框" class="headerlink" title="22 数据框"></a>22 数据框</h2><p>数据框是一种表格式的数据结构,</p>
<p>数据集通常是由数据构成的一个矩形数组,行表示观测,列表示变量.不同的行业对于数据集的行列叫法不同.</p>
<p>数据框实际上是一个列表.列表中的元素就是向量,这些向量构成数据框的列,每一列的长度相同,数据框的列是必须命名的.</p>
<p>比如excel中的数据表就是一个数据框,其中的每一列的元素格式可以不同.</p>
<p>矩阵的数据必须是一个类型,数据框可以不同,数据框的每一列必须是同一类型,每一行可以不同.</p>
<p>生成数据框</p>
<pre class="line-numbers language-R" data-language="R"><code class="language-R">state &#x3D; data.frame(state.name,state.abb,state.region,state.x77)<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p>数据框的访问,基本是一样的</p>
<pre class="line-numbers language-R" data-language="R"><code class="language-R">&gt; state[1] 输出第一列
&gt; state[c(2,4)]  输出2和4列
&gt; state[,&quot;state.abb&quot;]
&gt; state$state.abb  采用$符号的方式访问<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>

<p>与plot函数使用的实例,绘制women的身高体重散点图</p>
<pre class="line-numbers language-R" data-language="R"><code class="language-R">plot(women$height,women$weight) <span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<!--<img src="https://s1.ax1x.com/2020/05/28/teuy7t.png" alt="teuy7t.png" border="0" />-->
<p><img src="https://s1.ax1x.com/2020/05/28/teuy7t.png" alt="teuy7t.png"></p>
<h4 id="不使用-符号的各种操作"><a href="#不使用-符号的各种操作" class="headerlink" title="不使用$符号的各种操作"></a>不使用$符号的各种操作</h4><p><code>attach</code>加载与<code>detach</code>取消加载;可以在终端中直接敲数据框的名字就可以了,就可以摆脱$符号</p>
<pre class="line-numbers language-R" data-language="R"><code class="language-R">&gt; attach(mtcars)
&gt; mpg  数据框的名称
 [1] 21.0 21.0 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 17.8 16.4 17.3 15.2 10.4
[16] 10.4 14.7 32.4 30.4 33.9 21.5 15.5 15.2 13.3 19.2 27.3 26.0 30.4 15.8 19.7
[31] 15.0 21.4<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p><code>with</code>函数,不过要一个一个的加载,一般还是推荐使用$符号</p>
<pre class="line-numbers language-R" data-language="R"><code class="language-R">&gt; with(mtcars,&#123;hp&#125;)
&gt; hp
 [1] 110 110  93 110 175 105 245  62  95 123 123 180 180 180 205 215 230  66  52
[20]  65  97 150 150 245 175  66  91 113 264 175 335 109<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>
<p>关于单双括号的解释,就像使火车,单括号还是访问的火车中的车厢,双括号就相当于把车厢取出来单独使用.</p>
<h2 id="23-因子"><a href="#23-因子" class="headerlink" title="23 因子"></a>23 因子</h2><p>R中的因子使不好理解的</p>
<p>变量的分类</p>
<ol>
<li>名义型变量:一般为字符串</li>
<li>有序型变量</li>
<li>连续型变量:一般为数值型</li>
</ol>
<p>在R中名义型变量和有序型变量称为因子,factor. 这些分类变量的可能值称为一个水平,level,例如good,better,best,都称为一个level. 有这些水平值构成的向量就称为因子.</p>
<p>因子的应用</p>
<ul>
<li>计算频数</li>
<li>独立性检验</li>
<li>相关性检验</li>
<li>方差分析</li>
<li>主成分分析</li>
<li>因子分析等</li>
</ul>
<p>table频数统计.cyl就是一个因子,4,6,8就是水平</p>
<pre class="line-numbers language-R" data-language="R"><code class="language-R">&gt; mtcars$cyl
 [1] 6 6 4 6 8 6 8 4 4 6 6 8 8 8 8 8 8 4 4 4 4 8 8 8 8 4 4 4 8 6 8 4
&gt; table(cyl)
cyl
 4  6  8 
11  7 14 <span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>factor 函数可以将向量函数转换成因子,按照顺序排列</p>
<pre class="line-numbers language-R" data-language="R"><code class="language-R">&gt; week &#x3D; factor(c(&quot;Mon&quot;,&quot;Fri&quot;,&quot;Tuh&quot;,&quot;Wed&quot;,&quot;Mon&quot;,&quot;Fri&quot;,&quot;Sun&quot;),ordered &#x3D; T,levels &#x3D; c(&quot;Mon&quot;,&quot;Tue&quot;,&quot;Wed&quot;,&quot;Thu&quot;,&quot;Fri&quot;,&quot;Sat&quot;,&quot;Sun&quot;))
&gt; week
[1] Mon  Fri  &lt;NA&gt; Wed  Mon  Fri  Sun 
Levels: Mon &lt; Tue &lt; Wed &lt; Thu &lt; Fri &lt; Sat &lt; Sun
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>

<p>水平</p>
<pre class="line-numbers language-R" data-language="R"><code class="language-R">&gt; fcyl &#x3D; factor(mtcars$cyl)
&gt; fcyl 
 [1] 6 6 4 6 8 6 8 4 4 6 6 8 8 8 8 8 8 4 4 4 4 8 8 8 8 4 4 4 8 6 8
[32] 4
Levels: 4 6 8<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>通过水平绘制柱状图,可以很好的进行频数统计</p>
<pre class="line-numbers language-R" data-language="R"><code class="language-R">&gt; fcyl &#x3D; factor(mtcars$cyl)
&gt; fcyl 
 [1] 6 6 4 6 8 6 8 4 4 6 6 8 8 8 8 8 8 4 4 4 4 8 8 8 8 4 4 4 8 6 8
[32] 4
Levels: 4 6 8
&gt; plot(fcyl )<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<!--<img src="https://s1.ax1x.com/2020/06/01/t861js.png" alt="t861js.png" border="0" />-->
<p><img src="https://s1.ax1x.com/2020/06/01/t861js.png" alt="t861js.png"></p>
<pre class="line-numbers language-R" data-language="R"><code class="language-R">&gt; num &#x3D; 1:100
&gt; cut(num,c(seq(0,100,10)))
  [1] (0,10]   (0,10]   (0,10]   (0,10]   (0,10]   (0,10]   (0,10]   (0,10]   (0,10]   (0,10]   (10,20]  (10,20]  (10,20]  (10,20]  (10,20] 
 [16] (10,20]  (10,20]  (10,20]  (10,20]  (10,20]  (20,30]  (20,30]  (20,30]  (20,30]  (20,30]  (20,30]  (20,30]  (20,30]  (20,30]  (20,30] 
 ...<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>state.divsion和state.region,也是factor的内置数据</p>
<h2 id="24-缺失数据"><a href="#24-缺失数据" class="headerlink" title="24-缺失数据"></a>24-缺失数据</h2><p>缺失数据可分为</p>
<ul>
<li>完全随机缺失</li>
<li>随机缺失</li>
<li>非随机缺失<br>缺失可能是设备故障,测量的问题导致的</li>
</ul>
<p><code>NA</code>表示缺失not available的简称,不是没有值,知识未知的数值.</p>
<p>统计的时候跳过缺失值,但是平均值的时候还是按照全部的值的个数计算的.</p>
<pre class="line-numbers language-R" data-language="R"><code class="language-R">&gt; a &#x3D; c(NA,1:49)
&gt; sum(a)
[1] NA
&gt; sum(a,na.rm &#x3D; TRUE)
[1] 1225
&gt; mean(a,na.rm &#x3D; TRUE)
[1] 25<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>用<code>na.omit()</code>去除缺失值</p>
<pre class="line-numbers language-R" data-language="R"><code class="language-R">&gt; c &#x3D; c(NA,1:20,NA,NA)
&gt; c
 [1] NA  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20
[22] NA NA
&gt; d &#x3D; na.omit(c)
&gt; d
 [1]  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20
attr(,&quot;na.action&quot;)
[1]  1 22 23
attr(,&quot;class&quot;)
[1] &quot;omit&quot;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h4 id="其他缺失数据"><a href="#其他缺失数据" class="headerlink" title="其他缺失数据"></a>其他缺失数据</h4><ol>
<li>缺失数据NaN,代表不可能的值;</li>
<li>Inf表示无穷,分为正无穷Inf和负无穷Inf,代表无穷大或者无穷小.</li>
<li>Inf存在,是无穷大后者无穷小,但是表示不可能的值.</li>
</ol>
<ul>
<li>可以用<code>is.nan()</code>来识别不可能值</li>
<li>可以用<code>is.infinite()</code>来识别无穷值</li>
</ul>
<h2 id="25-字符串"><a href="#25-字符串" class="headerlink" title="25-字符串"></a>25-字符串</h2><p>R中可用的正则表达式</p>
<!--<img src="https://s1.ax1x.com/2020/06/01/tJHIUS.png" alt="tJHIUS.png" border="0" />-->
<p><img src="https://s1.ax1x.com/2020/06/01/tJHIUS.png" alt="tJHIUS.png"></p>
<p>统计字符串的长度,包括字符串</p>
<pre class="line-numbers language-R" data-language="R"><code class="language-R">&gt; nchar(&quot;hello world&quot;)
[1] 11

&gt; nchar(month.name)  ## 可以返回向量的每个元素的长度,length不可以
 [1] 7 8 5 5 3 4 4 6 9 7 8 8
&gt; length(month.name)
[1] 12<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p><code>paste()</code>可以把字符串相连</p>
<pre class="line-numbers language-R" data-language="R"><code class="language-R">### paste() 后面的参数都会与变量的每个元素连接
&gt; name &#x3D; c(&quot;Moe&quot;,&quot;Larry&quot;,&quot;Curly&quot;)
&gt; paste(name,&quot;loves stats&quot;)
[1] &quot;Moe loves stats&quot;   &quot;Larry loves stats&quot; &quot;Curly loves stats&quot;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>

<p>用<code>substr()</code>提取字符,可以提取每一个元素的字符</p>
<pre class="line-numbers language-R" data-language="R"><code class="language-R">### start 表示起始位置,stop表示终止位置
&gt; substr(x &#x3D; month.name,start &#x3D; 1,stop &#x3D; 3)
 [1] &quot;Jan&quot; &quot;Feb&quot; &quot;Mar&quot; &quot;Apr&quot; &quot;May&quot; &quot;Jun&quot; &quot;Jul&quot; &quot;Aug&quot; &quot;Sep&quot; &quot;Oct&quot;
[11] &quot;Nov&quot; &quot;Dec&quot;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>

<p>大小写<code>tolower()</code>和<code>toupper()</code>和首字母大写</p>
<pre class="line-numbers language-R" data-language="R"><code class="language-R">&gt; temp &#x3D; substr(x &#x3D; month.name,start &#x3D; 1,stop &#x3D; 3)
&gt; temp
 [1] &quot;Jan&quot; &quot;Feb&quot; &quot;Mar&quot; &quot;Apr&quot; &quot;May&quot; &quot;Jun&quot; &quot;Jul&quot; &quot;Aug&quot; &quot;Sep&quot; &quot;Oct&quot;
[11] &quot;Nov&quot; &quot;Dec&quot;
&gt; tolower(temp)
 [1] &quot;jan&quot; &quot;feb&quot; &quot;mar&quot; &quot;apr&quot; &quot;may&quot; &quot;jun&quot; &quot;jul&quot; &quot;aug&quot; &quot;sep&quot; &quot;oct&quot;
[11] &quot;nov&quot; &quot;dec&quot;
&gt; toupper(temp)
 [1] &quot;JAN&quot; &quot;FEB&quot; &quot;MAR&quot; &quot;APR&quot; &quot;MAY&quot; &quot;JUN&quot; &quot;JUL&quot; &quot;AUG&quot; &quot;SEP&quot; &quot;OCT&quot;
[11] &quot;NOV&quot; &quot;DEC&quot;

### 首字母大写不是很好解决,可以用正则替换，perl &#x3D; T表示支持perl语言的正则表达式
&gt; gsub(&quot;^(\\w)&quot;,&quot;\\L\\1&quot;,tolower(temp),perl &#x3D; T)
 [1] &quot;jan&quot; &quot;feb&quot; &quot;mar&quot; &quot;apr&quot; &quot;may&quot; &quot;jun&quot; &quot;jul&quot; &quot;aug&quot; &quot;sep&quot; &quot;oct&quot;
[11] &quot;nov&quot; &quot;dec&quot;
&gt; gsub(&quot;^(\\w)&quot;,&quot;\\U\\1&quot;,tolower(temp),perl &#x3D; T)
 [1] &quot;Jan&quot; &quot;Feb&quot; &quot;Mar&quot; &quot;Apr&quot; &quot;May&quot; &quot;Jun&quot; &quot;Jul&quot; &quot;Aug&quot; &quot;Sep&quot; &quot;Oct&quot;
[11] &quot;Nov&quot; &quot;Dec&quot;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p><code>grep()</code>可以用来搜索字符串,其次还有<code>match()</code></p>
<pre class="line-numbers language-R" data-language="R"><code class="language-R">&gt; x &#x3D; c(&quot;b&quot;,&quot;A+&quot;,&quot;AC&quot;)
&gt; grep(&quot;b&quot;,x,fixed &#x3D; T)
[1] 1<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>

<p><code>strsplit()</code>可以用来分割字符串,返回一个列表,跟Python一个意思</p>
<pre class="line-numbers language-R" data-language="R"><code class="language-R">&gt; path &#x3D; &quot;&#x2F;usr&#x2F;local&#x2F;bin&#x2F;R&quot;
&gt; strsplit(path,&quot;&#x2F;&quot;)
[[1]]
[1] &quot;&quot;      &quot;usr&quot;   &quot;local&quot; &quot;bin&quot;   &quot;R&quot;  <span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>

<p>后语:正则表达式是很重要的技能</p>
<p>附赠技能:随机字符串,比如生成一副扑克牌</p>
<pre class="line-numbers language-r" data-language="r"><code class="language-r"><span class="token operator">></span> face <span class="token operator">=</span> <span class="token number">1</span><span class="token operator">:</span><span class="token number">13</span>
<span class="token operator">></span> suit <span class="token operator">=</span> c<span class="token punctuation">(</span><span class="token string">"spades"</span><span class="token punctuation">,</span><span class="token string">"clubs"</span><span class="token punctuation">,</span><span class="token string">"hearts"</span><span class="token punctuation">,</span><span class="token string">"diamonds"</span><span class="token punctuation">)</span>

<span class="token comment">### FUN表示接一个函数,这里是连接函数,sep表示连接符号</span>
<span class="token operator">></span> outer<span class="token punctuation">(</span>suit<span class="token punctuation">,</span>face<span class="token punctuation">,</span>FUN <span class="token operator">=</span> paste<span class="token punctuation">,</span>sep<span class="token operator">=</span><span class="token string">"-"</span><span class="token punctuation">)</span>
     <span class="token punctuation">[</span><span class="token punctuation">,</span><span class="token number">1</span><span class="token punctuation">]</span>         <span class="token punctuation">[</span><span class="token punctuation">,</span><span class="token number">2</span><span class="token punctuation">]</span>         <span class="token punctuation">[</span><span class="token punctuation">,</span><span class="token number">3</span><span class="token punctuation">]</span>         <span class="token punctuation">[</span><span class="token punctuation">,</span><span class="token number">4</span><span class="token punctuation">]</span>        
<span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">,</span><span class="token punctuation">]</span> <span class="token string">"spades-1"</span>   <span class="token string">"spades-2"</span>   <span class="token string">"spades-3"</span>   <span class="token string">"spades-4"</span>  
<span class="token punctuation">[</span><span class="token number">2</span><span class="token punctuation">,</span><span class="token punctuation">]</span> <span class="token string">"clubs-1"</span>    <span class="token string">"clubs-2"</span>    <span class="token string">"clubs-3"</span>    <span class="token string">"clubs-4"</span>   
<span class="token punctuation">[</span><span class="token number">3</span><span class="token punctuation">,</span><span class="token punctuation">]</span> <span class="token string">"hearts-1"</span>   <span class="token string">"hearts-2"</span>   <span class="token string">"hearts-3"</span>   <span class="token string">"hearts-4"</span>  
<span class="token punctuation">[</span><span class="token number">4</span><span class="token punctuation">,</span><span class="token punctuation">]</span> <span class="token string">"diamonds-1"</span> <span class="token string">"diamonds-2"</span> <span class="token string">"diamonds-3"</span> <span class="token string">"diamonds-4"</span>
     <span class="token punctuation">[</span><span class="token punctuation">,</span><span class="token number">5</span><span class="token punctuation">]</span>         <span class="token punctuation">[</span><span class="token punctuation">,</span><span class="token number">6</span><span class="token punctuation">]</span>         <span class="token punctuation">[</span><span class="token punctuation">,</span><span class="token number">7</span><span class="token punctuation">]</span>         <span class="token punctuation">[</span><span class="token punctuation">,</span><span class="token number">8</span><span class="token punctuation">]</span>        
<span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">,</span><span class="token punctuation">]</span> <span class="token string">"spades-5"</span>   <span class="token string">"spades-6"</span>   <span class="token string">"spades-7"</span>   <span class="token string">"spades-8"</span>  
<span class="token punctuation">[</span><span class="token number">2</span><span class="token punctuation">,</span><span class="token punctuation">]</span> <span class="token string">"clubs-5"</span>    <span class="token string">"clubs-6"</span>    <span class="token string">"clubs-7"</span>    <span class="token string">"clubs-8"</span>   
<span class="token punctuation">[</span><span class="token number">3</span><span class="token punctuation">,</span><span class="token punctuation">]</span> <span class="token string">"hearts-5"</span>   <span class="token string">"hearts-6"</span>   <span class="token string">"hearts-7"</span>   <span class="token string">"hearts-8"</span>  
<span class="token punctuation">[</span><span class="token number">4</span><span class="token punctuation">,</span><span class="token punctuation">]</span> <span class="token string">"diamonds-5"</span> <span class="token string">"diamonds-6"</span> <span class="token string">"diamonds-7"</span> <span class="token string">"diamonds-8"</span>
     <span class="token punctuation">[</span><span class="token punctuation">,</span><span class="token number">9</span><span class="token punctuation">]</span>         <span class="token punctuation">[</span><span class="token punctuation">,</span><span class="token number">10</span><span class="token punctuation">]</span>         <span class="token punctuation">[</span><span class="token punctuation">,</span><span class="token number">11</span><span class="token punctuation">]</span>         <span class="token punctuation">[</span><span class="token punctuation">,</span><span class="token number">12</span><span class="token punctuation">]</span>        
<span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">,</span><span class="token punctuation">]</span> <span class="token string">"spades-9"</span>   <span class="token string">"spades-10"</span>   <span class="token string">"spades-11"</span>   <span class="token string">"spades-12"</span>  
<span class="token punctuation">[</span><span class="token number">2</span><span class="token punctuation">,</span><span class="token punctuation">]</span> <span class="token string">"clubs-9"</span>    <span class="token string">"clubs-10"</span>    <span class="token string">"clubs-11"</span>    <span class="token string">"clubs-12"</span>   
<span class="token punctuation">[</span><span class="token number">3</span><span class="token punctuation">,</span><span class="token punctuation">]</span> <span class="token string">"hearts-9"</span>   <span class="token string">"hearts-10"</span>   <span class="token string">"hearts-11"</span>   <span class="token string">"hearts-12"</span>  
<span class="token punctuation">[</span><span class="token number">4</span><span class="token punctuation">,</span><span class="token punctuation">]</span> <span class="token string">"diamonds-9"</span> <span class="token string">"diamonds-10"</span> <span class="token string">"diamonds-11"</span> <span class="token string">"diamonds-12"</span>
     <span class="token punctuation">[</span><span class="token punctuation">,</span><span class="token number">13</span><span class="token punctuation">]</span>        
<span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">,</span><span class="token punctuation">]</span> <span class="token string">"spades-13"</span>  
<span class="token punctuation">[</span><span class="token number">2</span><span class="token punctuation">,</span><span class="token punctuation">]</span> <span class="token string">"clubs-13"</span>   
<span class="token punctuation">[</span><span class="token number">3</span><span class="token punctuation">,</span><span class="token punctuation">]</span> <span class="token string">"hearts-13"</span>  
<span class="token punctuation">[</span><span class="token number">4</span><span class="token punctuation">,</span><span class="token punctuation">]</span> <span class="token string">"diamonds-13"</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h2 id="26-日期和时间"><a href="#26-日期和时间" class="headerlink" title="26-日期和时间"></a>26-日期和时间</h2><p><strong>主要两点</strong>:</p>
<ol>
<li>对时间序列的描述;一段时间内发生了什么.</li>
<li>利用前面的结果预测,预测接下来要发生什么.</li>
</ol>
<p>R包的分类中Task Views有很多的处理时间分析的包</p>
<p><code>airmiles</code>内置数据集就是一个专门的Time Series:的时间数据集.</p>
<p><code>Sys.Date()</code>可以显示现在的时间</p>
<p>格式化日期类型</p>
<pre class="line-numbers language-r" data-language="r"><code class="language-r"><span class="token operator">></span> a <span class="token operator">=</span> <span class="token string">"2017-01-01"</span>  <span class="token comment">## 这是一个字符串类型</span>
<span class="token operator">></span> as.Date<span class="token punctuation">(</span>a<span class="token punctuation">,</span>format <span class="token operator">=</span> <span class="token string">"%Y-%m-%d"</span><span class="token punctuation">)</span>
<span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">]</span> <span class="token string">"2017-01-01"</span>
<span class="token operator">></span> class<span class="token punctuation">(</span>as.Date<span class="token punctuation">(</span>a<span class="token punctuation">,</span>format <span class="token operator">=</span> <span class="token string">"%Y-%m-%d"</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
<span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">]</span> <span class="token string">"Date"</span>  <span class="token comment">## 这是一个日期类型</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>更多格式化日期的参数可以查看<code>?strftime</code></p>
<p>可以用<code>seq()</code>创建一个连续的时间序列，创建连续的时间点:</p>
<pre class="line-numbers language-r" data-language="r"><code class="language-r"><span class="token operator">></span> seq<span class="token punctuation">(</span>as.Date<span class="token punctuation">(</span><span class="token string">"2017-01-01"</span><span class="token punctuation">)</span><span class="token punctuation">,</span>as.Date<span class="token punctuation">(</span><span class="token string">"2017-07-05"</span><span class="token punctuation">)</span><span class="token punctuation">,</span>by<span class="token operator">=</span><span class="token number">5</span><span class="token punctuation">)</span>
 <span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">]</span> <span class="token string">"2017-01-01"</span> <span class="token string">"2017-01-06"</span> <span class="token string">"2017-01-11"</span>
 <span class="token punctuation">[</span><span class="token number">4</span><span class="token punctuation">]</span> <span class="token string">"2017-01-16"</span> <span class="token string">"2017-01-21"</span> <span class="token string">"2017-01-26"</span>
 <span class="token punctuation">[</span><span class="token number">7</span><span class="token punctuation">]</span> <span class="token string">"2017-01-31"</span> <span class="token string">"2017-02-05"</span> <span class="token string">"2017-02-10"</span>
<span class="token punctuation">[</span><span class="token number">10</span><span class="token punctuation">]</span> <span class="token string">"2017-02-15"</span> <span class="token string">"2017-02-20"</span> <span class="token string">"2017-02-25"</span>
<span class="token punctuation">[</span><span class="token number">13</span><span class="token punctuation">]</span> <span class="token string">"2017-03-02"</span> <span class="token string">"2017-03-07"</span> <span class="token string">"2017-03-12"</span>
<span class="token punctuation">[</span><span class="token number">16</span><span class="token punctuation">]</span> <span class="token string">"2017-03-17"</span> <span class="token string">"2017-03-22"</span> <span class="token string">"2017-03-27"</span>
<span class="token punctuation">[</span><span class="token number">19</span><span class="token punctuation">]</span> <span class="token string">"2017-04-01"</span> <span class="token string">"2017-04-06"</span> <span class="token string">"2017-04-11"</span>
<span class="token punctuation">[</span><span class="token number">22</span><span class="token punctuation">]</span> <span class="token string">"2017-04-16"</span> <span class="token string">"2017-04-21"</span> <span class="token string">"2017-04-26"</span>
<span class="token punctuation">[</span><span class="token number">25</span><span class="token punctuation">]</span> <span class="token string">"2017-05-01"</span> <span class="token string">"2017-05-06"</span> <span class="token string">"2017-05-11"</span>
<span class="token punctuation">[</span><span class="token number">28</span><span class="token punctuation">]</span> <span class="token string">"2017-05-16"</span> <span class="token string">"2017-05-21"</span> <span class="token string">"2017-05-26"</span>
<span class="token punctuation">[</span><span class="token number">31</span><span class="token punctuation">]</span> <span class="token string">"2017-05-31"</span> <span class="token string">"2017-06-05"</span> <span class="token string">"2017-06-10"</span>
<span class="token punctuation">[</span><span class="token number">34</span><span class="token punctuation">]</span> <span class="token string">"2017-06-15"</span> <span class="token string">"2017-06-20"</span> <span class="token string">"2017-06-25"</span>
<span class="token punctuation">[</span><span class="token number">37</span><span class="token punctuation">]</span> <span class="token string">"2017-06-30"</span> <span class="token string">"2017-07-05"</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>随机生成48个数字</p>
<p>介绍了ts函数</p>
<h2 id="27-常见错误"><a href="#27-常见错误" class="headerlink" title="27-常见错误"></a>27-常见错误</h2><h4 id="问题"><a href="#问题" class="headerlink" title="问题:"></a>问题:</h4><ul>
<li>等号问题,复制操作,<code>==</code>表示判断是否相等</li>
<li>赋值问题</li>
<li>c函数问题</li>
<li>括号的问题</li>
<li>引号问题,引号内的一边为字符</li>
<li>安装包的时候要加引号<code>install.packages(&quot;gclus&quot;)</code></li>
<li>逗号问题,起一个分割作用</li>
<li>在windows中路径<code>/</code>为R中的转义符</li>
<li>包是需要载入的,</li>
<li>R中严格区分大小写</li>
</ul>
<h4 id="解决问题方法"><a href="#解决问题方法" class="headerlink" title="解决问题方法"></a>解决问题方法</h4><ul>
<li>google</li>
<li>Rblogger</li>
<li>quickR</li>
<li>stackoverflow等</li>
</ul>
<h2 id="28-获取数据"><a href="#28-获取数据" class="headerlink" title="28-获取数据"></a>28-获取数据</h2><p>获取途径:</p>
<ul>
<li>利用键盘来输入数据;</li>
<li>读取存储在外部的数据;</li>
<li>通过访问数据框系统来获取数据;</li>
</ul>
<p>前面的都不主流,主要是访问外部的文件,或者数据框的信息</p>
<p>通过ODBC 访问数据库,相当于数据库的一个驱动.<br><code>install.packages(&quot;RODBC&quot;)</code>就可以安装了,但是我这里报错了</p>
<p>这里讲的不是很详细</p>
<h2 id="29-读取文件-一"><a href="#29-读取文件-一" class="headerlink" title="29-读取文件(一)"></a>29-读取文件(一)</h2><p>R几乎可以读取所有的数据文件</p>
<p><code>setwd(dir)</code>来设置工作目录;<br>在工作目录下<code>x = read.table(&quot;input.txt&quot;)</code>就可以读取文件了,这里只是读取到内存中.</p>
<pre class="line-numbers language-r" data-language="r"><code class="language-r"><span class="token operator">></span> x <span class="token operator">=</span> read.table<span class="token punctuation">(</span><span class="token string">"c:/Users/theing/Desktop/input.txt"</span><span class="token punctuation">)</span>  <span class="token comment">## 这样也可以读取文件信息</span>

<span class="token operator">></span> head<span class="token punctuation">(</span>x<span class="token punctuation">)</span>  <span class="token comment">## 显示头部的信息</span>
<span class="token operator">></span> tail<span class="token punctuation">(</span>x<span class="token punctuation">,</span>n<span class="token operator">=</span><span class="token number">10</span><span class="token punctuation">)</span>  <span class="token comment">## 显示尾部的10行信息</span>

<span class="token operator">></span> x <span class="token operator">=</span> read.table<span class="token punctuation">(</span><span class="token string">"input.csv"</span><span class="token punctuation">,</span>sep<span class="token operator">=</span><span class="token string">","</span><span class="token punctuation">)</span>  <span class="token comment">## 可以读取以","分割的csv文件</span>
<span class="token operator">></span> x <span class="token operator">=</span> read.csv<span class="token punctuation">(</span><span class="token string">"input.csv"</span><span class="token punctuation">)</span>  <span class="token comment">## 这个一样的效果</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p><code>read.table()</code>的参数</p>
<ul>
<li>skip=5 可以跳过前面的行,从第六行读取数据</li>
<li>nrows=100 这样可以只读取前面100行.可以和skip 配合使用</li>
<li>na.strings 处理缺失值,</li>
<li>stringsAsFactors=False 用来控制字符串是否转换成因子,R会默认的将字符串转换成因子.所以要设置成false</li>
</ul>
<h2 id="30-读取文件-二"><a href="#30-读取文件-二" class="headerlink" title="30-读取文件(二)"></a>30-读取文件(二)</h2><p>read.table 也可以读取网络连接</p>
<p>老师展示了很多被墙了的链接,估计也是在暗示着什么</p>
<p>其次还介绍了foreign包,</p>
<p>如何搜索R的相关包</p>
<pre class="line-numbers language-r" data-language="r"><code class="language-r"><span class="token operator">></span> RSiteSearch<span class="token punctuation">(</span><span class="token string">"Matlab"</span><span class="token punctuation">)</span>
檢索查詢疑問已被提交给http<span class="token operator">:</span><span class="token operator">/</span><span class="token operator">/</span>search.r<span class="token operator">-</span>project.org
计算结果应很快就在瀏覽器里打开<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>

<p>读取剪切板的内容,</p>
<pre class="line-numbers language-r" data-language="r"><code class="language-r"><span class="token comment">## 比如你在excel中复制了一部分内容,就可以用这个功能</span>
<span class="token comment">## readCliboard() 就是读取剪切板的内容.</span>

<span class="token operator">></span> x <span class="token operator">=</span> read.table<span class="token punctuation">(</span><span class="token string">"clipboard"</span><span class="token punctuation">,</span>header <span class="token operator">=</span> T<span class="token punctuation">,</span>sep<span class="token operator">=</span><span class="token string">"\t"</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>

<p>读取一个压缩文本的文件,R也是可以直接读取的</p>
<pre class="line-numbers language-r" data-language="r"><code class="language-r"><span class="token operator">></span> read.table<span class="token punctuation">(</span>gzfile<span class="token punctuation">(</span><span class="token string">"input.txt.gz"</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p>如果遇到不标准的文件格式,可以用<code>readlines</code>和<code>scan</code></p>
<pre class="line-numbers language-r" data-language="r"><code class="language-r"><span class="token comment">## 可以限制读入的行数</span>
<span class="token operator">></span> readLines<span class="token punctuation">(</span><span class="token string">"input.csv"</span><span class="token punctuation">,</span>n<span class="token operator">=</span><span class="token number">15</span><span class="token punctuation">)</span>

<span class="token operator">></span> ?scan可以查看帮助<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>

<h2 id="31-写入文件"><a href="#31-写入文件" class="headerlink" title="31-写入文件"></a>31-写入文件</h2><p>基本就是使用<code>write</code>函数</p>
<pre class="line-numbers language-r" data-language="r"><code class="language-r"><span class="token operator">></span> write<span class="token punctuation">(</span>x<span class="token punctuation">,</span>file <span class="token operator">=</span> <span class="token string">"x.txt"</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p>可以用,基本和Python类似。</p>
<pre class="line-numbers language-r" data-language="r"><code class="language-r"><span class="token comment">## sep 表示分隔符，row.name 表示行号</span>
<span class="token operator">></span> write.table<span class="token punctuation">(</span>x<span class="token punctuation">,</span>file <span class="token operator">=</span> <span class="token string">"c:/sld/sdl/x.csv"</span><span class="token punctuation">,</span>sep <span class="token operator">=</span> <span class="token string">","</span><span class="token punctuation">,</span>row.name <span class="token operator">=</span> <span class="token boolean">FALSE</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<p>直接写成压缩文件,比如</p>
<pre class="line-numbers language-r" data-language="r"><code class="language-r"><span class="token operator">></span> write.table<span class="token punctuation">(</span>mtcars<span class="token punctuation">,</span>gzfile<span class="token punctuation">(</span><span class="token string">"newfile.txt.gz"</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<h2 id="32-读取excel文件"><a href="#32-读取excel文件" class="headerlink" title="32-读取excel文件"></a>32-读取excel文件</h2><p>excel也是一个很好的数据统计文件,大多时候别人都是excel,所以还是应该掌握处理excel的能力.</p>
<p>excel倒过来的时候用的csv格式</p>
<p>XLConnect包,excel包含工作簿和工作表,称为workbook,可以直接打开xlsx的文件, 注意这个包是需要安装java环境.个人觉得这个没必要,能用excel处理就用excel处理.</p>
<pre class="line-numbers language-r" data-language="r"><code class="language-r"><span class="token operator">></span> ex <span class="token operator">=</span> loadWorkbook<span class="token punctuation">(</span><span class="token string">"data.xlsx"</span><span class="token punctuation">)</span>
<span class="token operator">></span> readWorksheet<span class="token punctuation">(</span>ex<span class="token punctuation">,</span><span class="token number">1</span><span class="token punctuation">)</span>  <span class="token comment">## 1表示查看的第一个工作表</span>
<span class="token operator">></span> ?readWorksheet  <span class="token comment">##查看具体的功能介绍</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>

<p>编辑excel</p>
<p>分四步法</p>
<ul>
<li>用loadWorkbook创建一个工作簿</li>
<li>工作簿中创建工作表</li>
<li>用writeWorksheet工具把数据保存到工作表中</li>
<li>用seveWorkbook保存为excel文件<pre class="line-numbers language-r" data-language="r"><code class="language-r"><span class="token operator">></span> wb <span class="token operator">=</span> loadWorkbook<span class="token punctuation">(</span><span class="token string">"file.xlsx"</span><span class="token punctuation">,</span>create <span class="token operator">=</span> T<span class="token punctuation">)</span>
<span class="token operator">></span> createSheet<span class="token punctuation">(</span>wb<span class="token punctuation">,</span><span class="token string">"Sheet 1"</span><span class="token punctuation">)</span>
<span class="token operator">></span> wtiteWorksheet<span class="token punctuation">(</span>wb<span class="token punctuation">,</span>data<span class="token operator">=</span>mtcars<span class="token punctuation">,</span>sheet <span class="token operator">=</span> <span class="token string">"Sheet1"</span><span class="token punctuation">)</span>
<span class="token operator">></span> seveWorkbook<span class="token punctuation">(</span>wb<span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>
查看XLConnet的详细介绍<pre class="line-numbers language-r" data-language="r"><code class="language-r">vignette<span class="token punctuation">(</span><span class="token string">"XLConnect"</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre></li>
</ul>
<p>xlsx包的使用</p>
<pre class="line-numbers language-r" data-language="r"><code class="language-r"><span class="token comment">## 读取第一个工作表的1到100行的内容,sheetName指明工作表的名称.append是否追加写入(新的文件,还是更改表格).</span>
<span class="token operator">></span> library<span class="token punctuation">(</span>xlsx<span class="token punctuation">)</span>
<span class="token operator">></span> read.xlsx<span class="token punctuation">(</span><span class="token string">"data.xlsx"</span><span class="token punctuation">,</span><span class="token number">1</span><span class="token punctuation">,</span>startRow <span class="token operator">=</span> <span class="token number">1</span><span class="token punctuation">,</span>endRow <span class="token operator">=</span> <span class="token number">100</span><span class="token punctuation">)</span>
<span class="token operator">></span> write.xlsx<span class="token punctuation">(</span>x<span class="token punctuation">,</span>file <span class="token operator">=</span> <span class="token string">"rdata.xlsx"</span><span class="token punctuation">,</span>sheetName <span class="token operator">=</span> <span class="token string">"Sheet 1"</span><span class="token punctuation">,</span>append <span class="token operator">=</span> F<span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>

<h2 id="33-读写R格式的文档"><a href="#33-读写R格式的文档" class="headerlink" title="33-读写R格式的文档"></a>33-读写R格式的文档</h2><p>R有两种格式的文件,Rdata和RDS</p>
<p>RDS文件</p>
<pre class="line-numbers language-r" data-language="r"><code class="language-r"><span class="token operator">></span> saveRDS<span class="token punctuation">(</span>iris<span class="token punctuation">,</span>file<span class="token operator">=</span><span class="token string">"iris.RDS"</span><span class="token punctuation">)</span>
<span class="token operator">></span> readRDS<span class="token punctuation">(</span><span class="token string">"iris.RDS"</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<p>Rdata 文件,项目文件,使用load()加载,一般双击就可以打开了.</p>
<pre class="line-numbers language-r" data-language="r"><code class="language-r"><span class="token comment">## 示例</span>
<span class="token operator">></span> load<span class="token punctuation">(</span><span class="token string">".RData"</span><span class="token punctuation">)</span>
<span class="token operator">></span> save<span class="token punctuation">(</span>iris<span class="token punctuation">,</span>iris3<span class="token punctuation">,</span>file <span class="token operator">=</span> <span class="token string">"c:/Users/theing/Desktop/iris.Rdata"</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>

<p>保存镜像</p>
<pre class="line-numbers language-r" data-language="r"><code class="language-r">save.image<span class="token punctuation">(</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<h2 id="34-数据转换"><a href="#34-数据转换" class="headerlink" title="34-数据转换"></a>34-数据转换</h2><p>数据的收集和存储已经会了,这里开始数据的转换,转换后就可以分析数据了.</p>
<p>前面介绍是向量,矩阵,数组,数据框,列表,因子,时间序列,等的增删改查</p>
<pre class="line-numbers language-r" data-language="r"><code class="language-r"><span class="token operator">></span> cars32 <span class="token operator">=</span> read.csv<span class="token punctuation">(</span><span class="token string">"mtcars.csv"</span><span class="token punctuation">)</span>
<span class="token operator">></span> is.data.frame<span class="token punctuation">(</span>cars32<span class="token punctuation">)</span>
<span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">]</span> <span class="token boolean">TRUE</span>  <span class="token comment">## 表示是一个矩阵</span>
<span class="token operator">></span> is.data.frame<span class="token punctuation">(</span>state.x77<span class="token punctuation">)</span>
<span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">]</span> <span class="token boolean">FALSE</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>转换为数据框</p>
<pre class="line-numbers language-r" data-language="r"><code class="language-r"><span class="token operator">></span> dstate.x77 <span class="token operator">=</span> as.data.frame<span class="token punctuation">(</span>state.x77<span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p>转换为矩阵,变为字符串类型的矩阵</p>
<pre class="line-numbers language-r" data-language="r"><code class="language-r"><span class="token operator">></span> as.matrix<span class="token punctuation">(</span>data.frame<span class="token punctuation">(</span>state.region<span class="token punctuation">,</span>state.x77<span class="token punctuation">)</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p>methods查看内容</p>
<pre class="line-numbers language-r" data-language="r"><code class="language-r"><span class="token operator">></span> methods<span class="token punctuation">(</span>is<span class="token punctuation">)</span>
<span class="token operator">></span> methods<span class="token punctuation">(</span>as<span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<h4 id="向量是R种基本的数据类型-加上一个维度就是数组或者矩阵"><a href="#向量是R种基本的数据类型-加上一个维度就是数组或者矩阵" class="headerlink" title="向量是R种基本的数据类型,加上一个维度就是数组或者矩阵"></a>向量是R种基本的数据类型,加上一个维度就是数组或者矩阵</h4><pre class="line-numbers language-r" data-language="r"><code class="language-r"><span class="token comment">## > is.data.frame(state.x77)</span>
<span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">]</span> <span class="token boolean">FALSE</span>
<span class="token operator">></span> x <span class="token operator">=</span> state.abb
<span class="token operator">></span> dim<span class="token punctuation">(</span>x<span class="token punctuation">)</span> <span class="token operator">=</span> c<span class="token punctuation">(</span><span class="token number">5</span><span class="token punctuation">,</span><span class="token number">10</span><span class="token punctuation">)</span>

<span class="token comment">## 向量变因子</span>
<span class="token operator">></span> x <span class="token operator">=</span> state.babb
<span class="token operator">></span> as.factor<span class="token punctuation">(</span>x<span class="token punctuation">)</span>

<span class="token comment">## 变为列表</span>
<span class="token operator">></span> as.list<span class="token punctuation">(</span>x<span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>添加一个数据框</p>
<pre class="line-numbers language-r" data-language="r"><code class="language-r"><span class="token operator">></span> state <span class="token operator">=</span> data.frame<span class="token punctuation">(</span>x<span class="token punctuation">,</span>state.region<span class="token punctuation">,</span>state.x77<span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<h2 id="35-数据转换-二"><a href="#35-数据转换-二" class="headerlink" title="35-数据转换(二)"></a>35-数据转换(二)</h2><p>讲一个取子集的操作</p>
<pre class="line-numbers language-r" data-language="r"><code class="language-r"><span class="token comment">## 这是一个数据框</span>
<span class="token operator">></span> who <span class="token operator">=</span> read.csv<span class="token punctuation">(</span><span class="token string">"WHO.csv"</span><span class="token punctuation">,</span>header <span class="token operator">=</span> T<span class="token punctuation">)</span>
<span class="token operator">></span> who1 <span class="token operator">=</span> who<span class="token punctuation">[</span>c<span class="token punctuation">(</span><span class="token number">1</span><span class="token operator">:</span><span class="token number">50</span><span class="token punctuation">)</span><span class="token punctuation">,</span>c<span class="token punctuation">(</span><span class="token number">1</span><span class="token operator">:</span><span class="token number">10</span><span class="token punctuation">)</span><span class="token punctuation">]</span>
<span class="token operator">></span> who2 <span class="token operator">=</span> who<span class="token punctuation">[</span>c<span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">,</span><span class="token number">3</span><span class="token punctuation">,</span><span class="token number">5</span><span class="token punctuation">,</span><span class="token number">8</span><span class="token punctuation">)</span><span class="token punctuation">,</span>c<span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">,</span><span class="token number">14</span><span class="token punctuation">,</span><span class="token number">16</span><span class="token punctuation">)</span><span class="token punctuation">]</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>

<p>取出CountryID 在50到100的国家,似乎不知道怎么去理解</p>
<pre class="line-numbers language-r" data-language="r"><code class="language-r"><span class="token operator">></span> who4 <span class="token operator">=</span> who<span class="token punctuation">[</span>which<span class="token punctuation">,</span><span class="token punctuation">(</span>who<span class="token operator">$</span>CountryID <span class="token operator">></span> <span class="token number">50</span> <span class="token operator">&amp;</span> who<span class="token operator">$</span>CountryID <span class="token operator">&lt;=</span><span class="token number">100</span><span class="token punctuation">)</span><span class="token punctuation">]</span>
<span class="token operator">></span> who4 <span class="token operator">=</span> subset<span class="token punctuation">(</span>who<span class="token punctuation">,</span>who<span class="token operator">$</span>CountryID <span class="token operator">></span> <span class="token number">50</span> <span class="token operator">&amp;</span> who<span class="token operator">$</span>CountryID <span class="token operator">&lt;=</span><span class="token number">100</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<p>sample抽样,机器学习中抽取两份样本,一份用来建模,一份用来验证模型的有效性</p>
<pre class="line-numbers language-r" data-language="r"><code class="language-r"><span class="token operator">></span> ?sample
<span class="token comment">## 例子,第一个参数为是选择那个向量,第二个是要抽取的个数,replace 表示是否放回式的抽样.</span>
<span class="token operator">></span> x <span class="token operator">=</span> <span class="token number">1</span><span class="token operator">:</span><span class="token number">100</span>
<span class="token operator">></span> sample<span class="token punctuation">(</span>x<span class="token punctuation">,</span><span class="token number">30</span><span class="token punctuation">,</span>replace <span class="token operator">=</span> T<span class="token punctuation">)</span>
 <span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">]</span> <span class="token number">39</span> <span class="token number">23</span> <span class="token number">11</span> <span class="token number">26</span> <span class="token number">50</span> <span class="token number">86</span> <span class="token number">86</span> <span class="token number">71</span> <span class="token number">26</span>  <span class="token number">6</span> <span class="token number">10</span> <span class="token number">93</span> <span class="token number">81</span> <span class="token number">73</span> <span class="token number">74</span> <span class="token number">87</span> <span class="token number">98</span>
<span class="token punctuation">[</span><span class="token number">18</span><span class="token punctuation">]</span>  <span class="token number">6</span> <span class="token number">17</span> <span class="token number">87</span> <span class="token number">10</span> <span class="token number">69</span> <span class="token number">51</span> <span class="token number">24</span> <span class="token number">22</span> <span class="token number">70</span> <span class="token number">33</span> <span class="token number">68</span> <span class="token number">97</span> <span class="token number">82</span>
<span class="token operator">></span> sort<span class="token punctuation">(</span>sample<span class="token punctuation">(</span>x<span class="token punctuation">,</span><span class="token number">30</span><span class="token punctuation">,</span>replace <span class="token operator">=</span> T<span class="token punctuation">)</span><span class="token punctuation">)</span>
 <span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">]</span>  <span class="token number">8</span> <span class="token number">19</span> <span class="token number">23</span> <span class="token number">23</span> <span class="token number">28</span> <span class="token number">31</span> <span class="token number">32</span> <span class="token number">40</span> <span class="token number">40</span> <span class="token number">42</span> <span class="token number">50</span> <span class="token number">50</span> <span class="token number">50</span> <span class="token number">51</span> <span class="token number">52</span> <span class="token number">55</span> <span class="token number">58</span>
<span class="token punctuation">[</span><span class="token number">18</span><span class="token punctuation">]</span> <span class="token number">60</span> <span class="token number">63</span> <span class="token number">70</span> <span class="token number">73</span> <span class="token number">77</span> <span class="token number">78</span> <span class="token number">83</span> <span class="token number">83</span> <span class="token number">84</span> <span class="token number">85</span> <span class="token number">89</span> <span class="token number">93</span> <span class="token number">96</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>sample对数据框进行抽样,取子集</p>
<pre class="line-numbers language-r" data-language="r"><code class="language-r"><span class="token operator">></span> who<span class="token punctuation">[</span>sample<span class="token punctuation">(</span>who<span class="token operator">$</span>CountryID<span class="token punctuation">,</span><span class="token number">30</span><span class="token punctuation">,</span>replace <span class="token operator">=</span> F<span class="token punctuation">)</span><span class="token punctuation">,</span><span class="token punctuation">]</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p>删除固定行的数据</p>
<pre class="line-numbers language-r" data-language="r"><code class="language-r"><span class="token comment">## 注意逗号的位置</span>
<span class="token operator">></span> mtcars<span class="token punctuation">[</span><span class="token operator">-</span><span class="token number">1</span><span class="token operator">:</span><span class="token operator">-</span><span class="token number">5</span><span class="token punctuation">,</span><span class="token punctuation">]</span>

<span class="token comment">## 清空这一行的数据</span>
<span class="token operator">></span> mtcars<span class="token operator">$</span>mpg <span class="token operator">=</span> <span class="token keyword">NULL</span> <span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>如果遇到几个数据表进行汇总,这里要用到数据框的合并,可以使用cbind和rbind函数,cbind添加一列,rbind添加一行.</p>
<p>cbind合并列</p>
<pre class="line-numbers language-r" data-language="r"><code class="language-r"><span class="token comment">## USArrests是一个数据集,state.division是一个因子</span>
<span class="token operator">></span> cbind<span class="token punctuation">(</span>USArrests<span class="token punctuation">,</span>state.division<span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<p>rbind合并行,这个比较麻烦,需要所有的列有源数据集有相同的列名</p>
<pre class="line-numbers language-r" data-language="r"><code class="language-r"><span class="token comment">## 取出前20行和尾20行合并</span>
<span class="token operator">></span> data1 <span class="token operator">=</span> head<span class="token punctuation">(</span>USArrests<span class="token punctuation">,</span><span class="token number">20</span><span class="token punctuation">)</span>
<span class="token operator">></span> data2 <span class="token operator">=</span> head<span class="token punctuation">(</span>USArrests<span class="token punctuation">,</span><span class="token number">20</span><span class="token punctuation">)</span>
<span class="token operator">></span> b <span class="token operator">=</span> rbind<span class="token punctuation">(</span>data1<span class="token punctuation">,</span>data2<span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>

<p>cbind和rbind也可以用于矩阵</p>
<p>回顾rownames可以取出行名</p>
<p>判断向量和数据框中哪些是重复值</p>
<pre class="line-numbers language-r" data-language="r"><code class="language-r"><span class="token operator">></span> duplicated<span class="token punctuation">(</span>who<span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p>用unique(data4)可以一步取出重复项</p>
<h2 id="36-收据转换-三"><a href="#36-收据转换-三" class="headerlink" title="36-收据转换(三)"></a>36-收据转换(三)</h2><p>R中行列的调换,excel中可以复制后选择性粘贴.R中可以用<code>t()</code>函数实现转换</p>
<pre class="line-numbers language-r" data-language="r"><code class="language-r"><span class="token operator">></span> sractm <span class="token operator">=</span> t<span class="token punctuation">(</span>mtcars<span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p>单独一行的反转,生物序列中很常见,主要是反向互补,可以使用rev函,reverse的意思 </p>
<pre class="line-numbers language-r" data-language="r"><code class="language-r"><span class="token operator">></span> letters
 <span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">]</span> <span class="token string">"a"</span> <span class="token string">"b"</span> <span class="token string">"c"</span> <span class="token string">"d"</span> <span class="token string">"e"</span> <span class="token string">"f"</span> <span class="token string">"g"</span> <span class="token string">"h"</span> <span class="token string">"i"</span> <span class="token string">"j"</span> <span class="token string">"k"</span> <span class="token string">"l"</span>
<span class="token punctuation">[</span><span class="token number">13</span><span class="token punctuation">]</span> <span class="token string">"m"</span> <span class="token string">"n"</span> <span class="token string">"o"</span> <span class="token string">"p"</span> <span class="token string">"q"</span> <span class="token string">"r"</span> <span class="token string">"s"</span> <span class="token string">"t"</span> <span class="token string">"u"</span> <span class="token string">"v"</span> <span class="token string">"w"</span> <span class="token string">"x"</span>
<span class="token punctuation">[</span><span class="token number">25</span><span class="token punctuation">]</span> <span class="token string">"y"</span> <span class="token string">"z"</span>
<span class="token operator">></span> rev<span class="token punctuation">(</span>letters<span class="token punctuation">)</span>
 <span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">]</span> <span class="token string">"z"</span> <span class="token string">"y"</span> <span class="token string">"x"</span> <span class="token string">"w"</span> <span class="token string">"v"</span> <span class="token string">"u"</span> <span class="token string">"t"</span> <span class="token string">"s"</span> <span class="token string">"r"</span> <span class="token string">"q"</span> <span class="token string">"p"</span> <span class="token string">"o"</span>
<span class="token punctuation">[</span><span class="token number">13</span><span class="token punctuation">]</span> <span class="token string">"n"</span> <span class="token string">"m"</span> <span class="token string">"l"</span> <span class="token string">"k"</span> <span class="token string">"j"</span> <span class="token string">"i"</span> <span class="token string">"h"</span> <span class="token string">"g"</span> <span class="token string">"f"</span> <span class="token string">"e"</span> <span class="token string">"d"</span> <span class="token string">"c"</span>
<span class="token punctuation">[</span><span class="token number">25</span><span class="token punctuation">]</span> <span class="token string">"b"</span> <span class="token string">"a"</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>数据框中的数据反转,思路就是,提取行名,反转,以反转后的行名为索引</p>
<pre><code>&gt; rowname(women)
</code></pre>

                
            </div>
            <hr/>

            

    <div class="reprint" id="reprint-statement">
        
            <div class="reprint__author">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-user">
                        文章作者:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="/about" rel="external nofollow noreferrer">theing</a>
                </span>
            </div>
            <div class="reprint__type">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-link">
                        文章链接:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://theing.gitee.io/2020/06/26/r-shu-ju-fen-xi/r-yu-yan-ru-men-yu-shu-ju-fen-xi-bi-ji-yi/">https://theing.gitee.io/2020/06/26/r-shu-ju-fen-xi/r-yu-yan-ru-men-yu-shu-ju-fen-xi-bi-ji-yi/</a>
                </span>
            </div>
            <div class="reprint__notice">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-copyright">
                        版权声明:
                    </i>
                </span>
                <span class="reprint-info">
                    本博客所有文章除特別声明外，均采用
                    <a href="https://creativecommons.org/licenses/by/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY 4.0</a>
                    许可协议。转载请注明来源
                    <a href="/about" target="_blank">theing</a>
                    !
                </span>
            </div>
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>复制成功，请遵循本文的转载规则</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">查看</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>



            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            
                                <a href="/tags/R%E8%AF%AD%E8%A8%80%E6%95%B0%E6%8D%AE%E5%88%86%E6%9E%90/">
                                    <span class="chip bg-color">R语言数据分析</span>
                                </a>
                            
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <link rel="stylesheet" type="text/css" href="/libs/share/css/share.min.css">
<div id="article-share">

    
    <div class="social-share" data-sites="twitter,facebook,google,qq,qzone,wechat,weibo,douban,linkedin" data-wechat-qrcode-helper="<p>微信扫一扫即可分享！</p>"></div>
    <script src="/libs/share/js/social-share.min.js"></script>
    

    

</div>

                </div>
            </div>
            
        </div>
    </div>

    

    

    

    

    
        <style>
    .valine-card {
        margin: 1.5rem auto;
    }

    .valine-card .card-content {
        padding: 20px 20px 5px 20px;
    }

    #vcomments textarea {
        box-sizing: border-box;
        background: url("/medias/comment_bg.png") 100% 100% no-repeat;
    }

    #vcomments p {
        margin: 2px 2px 10px;
        font-size: 1.05rem;
        line-height: 1.78rem;
    }

    #vcomments blockquote p {
        text-indent: 0.2rem;
    }

    #vcomments a {
        padding: 0 2px;
        color: #4cbf30;
        font-weight: 500;
        text-decoration: none;
    }

    #vcomments img {
        max-width: 100%;
        height: auto;
        cursor: pointer;
    }

    #vcomments ol li {
        list-style-type: decimal;
    }

    #vcomments ol,
    ul {
        display: block;
        padding-left: 2em;
        word-spacing: 0.05rem;
    }

    #vcomments ul li,
    ol li {
        display: list-item;
        line-height: 1.8rem;
        font-size: 1rem;
    }

    #vcomments ul li {
        list-style-type: disc;
    }

    #vcomments ul ul li {
        list-style-type: circle;
    }

    #vcomments table, th, td {
        padding: 12px 13px;
        border: 1px solid #dfe2e5;
    }

    #vcomments table, th, td {
        border: 0;
    }

    table tr:nth-child(2n), thead {
        background-color: #fafafa;
    }

    #vcomments table th {
        background-color: #f2f2f2;
        min-width: 80px;
    }

    #vcomments table td {
        min-width: 80px;
    }

    #vcomments h1 {
        font-size: 1.85rem;
        font-weight: bold;
        line-height: 2.2rem;
    }

    #vcomments h2 {
        font-size: 1.65rem;
        font-weight: bold;
        line-height: 1.9rem;
    }

    #vcomments h3 {
        font-size: 1.45rem;
        font-weight: bold;
        line-height: 1.7rem;
    }

    #vcomments h4 {
        font-size: 1.25rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    #vcomments h5 {
        font-size: 1.1rem;
        font-weight: bold;
        line-height: 1.4rem;
    }

    #vcomments h6 {
        font-size: 1rem;
        line-height: 1.3rem;
    }

    #vcomments p {
        font-size: 1rem;
        line-height: 1.5rem;
    }

    #vcomments hr {
        margin: 12px 0;
        border: 0;
        border-top: 1px solid #ccc;
    }

    #vcomments blockquote {
        margin: 15px 0;
        border-left: 5px solid #42b983;
        padding: 1rem 0.8rem 0.3rem 0.8rem;
        color: #666;
        background-color: rgba(66, 185, 131, .1);
    }

    #vcomments pre {
        font-family: monospace, monospace;
        padding: 1.2em;
        margin: .5em 0;
        background: #272822;
        overflow: auto;
        border-radius: 0.3em;
        tab-size: 4;
    }

    #vcomments code {
        font-family: monospace, monospace;
        padding: 1px 3px;
        font-size: 0.92rem;
        color: #e96900;
        background-color: #f8f8f8;
        border-radius: 2px;
    }

    #vcomments pre code {
        font-family: monospace, monospace;
        padding: 0;
        color: #e8eaf6;
        background-color: #272822;
    }

    #vcomments pre[class*="language-"] {
        padding: 1.2em;
        margin: .5em 0;
    }

    #vcomments code[class*="language-"],
    pre[class*="language-"] {
        color: #e8eaf6;
    }

    #vcomments [type="checkbox"]:not(:checked), [type="checkbox"]:checked {
        position: inherit;
        margin-left: -1.3rem;
        margin-right: 0.4rem;
        margin-top: -1px;
        vertical-align: middle;
        left: unset;
        visibility: visible;
    }

    #vcomments b,
    strong {
        font-weight: bold;
    }

    #vcomments dfn {
        font-style: italic;
    }

    #vcomments small {
        font-size: 85%;
    }

    #vcomments cite {
        font-style: normal;
    }

    #vcomments mark {
        background-color: #fcf8e3;
        padding: .2em;
    }

    #vcomments table, th, td {
        padding: 12px 13px;
        border: 1px solid #dfe2e5;
    }

    table tr:nth-child(2n), thead {
        background-color: #fafafa;
    }

    #vcomments table th {
        background-color: #f2f2f2;
        min-width: 80px;
    }

    #vcomments table td {
        min-width: 80px;
    }

    #vcomments [type="checkbox"]:not(:checked), [type="checkbox"]:checked {
        position: inherit;
        margin-left: -1.3rem;
        margin-right: 0.4rem;
        margin-top: -1px;
        vertical-align: middle;
        left: unset;
        visibility: visible;
    }
</style>

<div class="card valine-card" data-aos="fade-up">
    <div class="comment_headling" style="font-size: 20px; font-weight: 700; position: relative; padding-left: 20px; top: 15px; padding-bottom: 5px;">
        <i class="fas fa-comments fa-fw" aria-hidden="true"></i>
        <span>评论</span>
    </div>
    <div id="vcomments" class="card-content" style="display: grid">
    </div>
</div>

<script src="/libs/valine/av-min.js"></script>
<script src="/libs/valine/Valine.min.js"></script>
<script>
    new Valine({
        el: '#vcomments',
        appId: 'c9A3NJapA0GqVqdjIanTXvWV-gzGzoHsz',
        appKey: 'siVPq9lDAGz8yClxLOmoMo6I',
        notify: 'true' === 'true',
        verify: 'true' === 'true',
        visitor: 'true' === 'true',
        avatar: 'mm',
        pageSize: '10',
        lang: 'zh-cn',
        placeholder: '随便说点什么吧！'
    });
</script>

<!--酷Q推送-->


    

    

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fas fa-chevron-left"></i>&nbsp;上一篇</div>
            <div class="card">
                <a href="/2020/06/26/r-shu-ju-fen-xi/r-yu-yan-ru-men-yu-shu-ju-fen-xi-bi-ji-er/">
                    <div class="card-image">
                        
                        <img src="/medias/featureimages/10.jpg" class="responsive-img" alt="R语言与数据分析（二）">
                        
                        <span class="card-title">R语言与数据分析（二）</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            
喜欢一件事就去争取吧。

                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="far fa-clock fa-fw icon-date"></i>2020-06-26
                        </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/%E6%95%B0%E6%8D%AE%E5%88%86%E6%9E%90/" class="post-category">
                                    数据分析
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/R%E8%AF%AD%E8%A8%80%E6%95%B0%E6%8D%AE%E5%88%86%E6%9E%90/">
                        <span class="chip bg-color">R语言数据分析</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                下一篇&nbsp;<i class="fas fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/2020/02/26/bei-wang/anaconda-chang-yong-ming-ling/">
                    <div class="card-image">
                        
                        <img src="/medias/featureimages/2.jpg" class="responsive-img" alt="anaconda常用命令">
                        
                        <span class="card-title">anaconda常用命令</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            
anaconda 一些常用命令和设置，如有不全请告知添加。

                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="far fa-clock fa-fw icon-date"></i>2020-02-26
                            </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/%E5%A4%87%E5%BF%98/" class="post-category">
                                    备忘
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/anaconda/">
                        <span class="chip bg-color">anaconda</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>

</div>



<!-- 代码块功能依赖 -->
<script type="text/javascript" src="/libs/codeBlock/codeBlockFuction.js"></script>

<!-- 代码语言 -->


<!-- 代码块复制 -->

<script type="text/javascript" src="/libs/codeBlock/codeCopy.js"></script>


<!-- 代码块收缩 -->


    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget card" ">
            <div class="toc-title"><i class="far fa-list-alt"></i>&nbsp;&nbsp;目录</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fas fa-list-ul"></i>
    </a>
</div>


<script src="/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            collapseDepth: Number('0'),
            headingSelector: 'h1, h2, h3, h4'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h1, h2, h3, h4').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).hide();
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).show();
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>

    

</main>




    <footer class="page-footer bg-color">
    
        <link rel="stylesheet" href="/libs/aplayer/APlayer.min.css">
<style>
    .aplayer .aplayer-lrc p {
        
        display: none;
        
        font-size: 12px;
        font-weight: 700;
        line-height: 16px !important;
    }

    .aplayer .aplayer-lrc p.aplayer-lrc-current {
        
        display: none;
        
        font-size: 15px;
        color: #42b983;
    }

    
    .aplayer.aplayer-fixed.aplayer-narrow .aplayer-body {
        left: -66px !important;
    }

    .aplayer.aplayer-fixed.aplayer-narrow .aplayer-body:hover {
        left: 0px !important;
    }

    
</style>
<div class="">
    
    <div class="row">
        <meting-js class="col l8 offset-l2 m10 offset-m1 s12"
                   server="tencent"
                   type="playlist"
                   id="694251243"
                   fixed='true'
                   autoplay='false'
                   theme='#42b983'
                   loop='all'
                   order='random'
                   preload='auto'
                   volume='0.5'
                   list-folded='false'
        >
        </meting-js>
    </div>
</div>

<script src="/libs/aplayer/APlayer.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/meting@2/dist/Meting.min.js"></script>

    

    <div class="container row center-align"
         style="margin-bottom: 0px !important;">
        <div class="col s12 m12 l12 copy-right">
            Copyright&nbsp;&copy;
            
                <span id="year">2019-2023</span>
            
            <span id="year">2019</span>
            <a href="/about" target="_blank">theing</a>
            |&nbsp;Powered by&nbsp;<a href="https://hexo.io/" target="_blank">Hexo</a>
            |&nbsp;Theme&nbsp;<a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">Matery</a>
            <br>
            
            
            
                
            
            
                <span id="busuanzi_container_site_pv">
                &nbsp;|&nbsp;<i class="far fa-eye"></i>&nbsp;总访问量:&nbsp;
                    <span id="busuanzi_value_site_pv" class="white-color"></span>
            </span>
            
            
                <span id="busuanzi_container_site_uv">
                &nbsp;|&nbsp;<i class="fas fa-users"></i>&nbsp;总访问人数:&nbsp;
                    <span id="busuanzi_value_site_uv" class="white-color"></span>
            </span>
            
            <br>

            <!-- 运行天数提醒. -->
            
            <br>
            
        </div>
        <!-- <div class="col s12 m4 l4 social-link social-statis">














</div> -->
    </div>
</footer>

<div class="progress-bar"></div>


    <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fas fa-search"></i>&nbsp;&nbsp;搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script type="text/javascript">
$(function () {
    var searchFunc = function (path, search_id, content_id) {
        'use strict';
        $.ajax({
            url: path,
            dataType: "xml",
            success: function (xmlResponse) {
                // get the contents from search data
                var datas = $("entry", xmlResponse).map(function () {
                    return {
                        title: $("title", this).text(),
                        content: $("content", this).text(),
                        url: $("url", this).text()
                    };
                }).get();
                var $input = document.getElementById(search_id);
                var $resultContent = document.getElementById(content_id);
                $input.addEventListener('input', function () {
                    var str = '<ul class=\"search-result-list\">';
                    var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
                    $resultContent.innerHTML = "";
                    if (this.value.trim().length <= 0) {
                        return;
                    }
                    // perform local searching
                    datas.forEach(function (data) {
                        var isMatch = true;
                        var data_title = data.title.trim().toLowerCase();
                        var data_content = data.content.trim().replace(/<[^>]+>/g, "").toLowerCase();
                        var data_url = data.url;
                        data_url = data_url.indexOf('/') === 0 ? data.url : '/' + data_url;
                        var index_title = -1;
                        var index_content = -1;
                        var first_occur = -1;
                        // only match artiles with not empty titles and contents
                        if (data_title !== '' && data_content !== '') {
                            keywords.forEach(function (keyword, i) {
                                index_title = data_title.indexOf(keyword);
                                index_content = data_content.indexOf(keyword);
                                if (index_title < 0 && index_content < 0) {
                                    isMatch = false;
                                } else {
                                    if (index_content < 0) {
                                        index_content = 0;
                                    }
                                    if (i === 0) {
                                        first_occur = index_content;
                                    }
                                }
                            });
                        }
                        // show search results
                        if (isMatch) {
                            str += "<li><a href='" + data_url + "' class='search-result-title'>" + data_title + "</a>";
                            var content = data.content.trim().replace(/<[^>]+>/g, "");
                            if (first_occur >= 0) {
                                // cut out 100 characters
                                var start = first_occur - 20;
                                var end = first_occur + 80;
                                if (start < 0) {
                                    start = 0;
                                }
                                if (start === 0) {
                                    end = 100;
                                }
                                if (end > content.length) {
                                    end = content.length;
                                }
                                var match_content = content.substr(start, end);
                                // highlight all keywords
                                keywords.forEach(function (keyword) {
                                    var regS = new RegExp(keyword, "gi");
                                    match_content = match_content.replace(regS, "<em class=\"search-keyword\">" + keyword + "</em>");
                                });

                                str += "<p class=\"search-result\">" + match_content + "...</p>"
                            }
                            str += "</li>";
                        }
                    });
                    str += "</ul>";
                    $resultContent.innerHTML = str;
                });
            }
        });
    };

    searchFunc('/search.xml', 'searchInput', 'searchResult');
});
</script>

    <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>


    <script src="/libs/materialize/materialize.min.js"></script>
    <script src="/libs/masonry/masonry.pkgd.min.js"></script>
    <script src="/libs/aos/aos.js"></script>
    <script src="/libs/scrollprogress/scrollProgress.min.js"></script>
    <script src="/libs/lightGallery/js/lightgallery-all.min.js"></script>
    <script src="/js/matery.js"></script>

    <!-- Baidu Analytics -->

    <!-- Baidu Push -->

    
    
    <script async src="/libs/others/busuanzi.pure.mini.js"></script>
    

    

    

    <!--腾讯兔小巢-->
    
    

    

    
    <script type="text/javascript" src="/libs/background/ribbon-dynamic.js" async="async"></script>
    

    
    <script src="/libs/instantpage/instantpage.js" type="module"></script>
    
    <canvas class="fireworks" style="position: fixed;left: 0;top: 0;z-index: 1; pointer-events: none;" ></canvas> 
    <script type="text/javascript" src="//cdn.bootcss.com/animejs/2.2.0/anime.min.js"></script> 
    <script type="text/javascript" src="/js/fireworks.js"></script>

</body>

</html>
